from flask import request
from flask import Flask
import json
import numpy as np
from http.server import HTTPServer, BaseHTTPRequestHandler
import cv2
import base64
from gevent.pywsgi import WSGIServer
import pymysql
app = Flask(__name__)

# 定义路由
@app.route("/photo", methods=['POST'])
def get_frame():
    # 接收图片
    # upload_file = json.loads(request.json)
    # print(upload_file['file'])
    # upload_file=request.form['file']
    jsonData=request.get_json()
    conn = pymysql.connect(host='localhost', user="root", password="qq371493316", database="VILAS", port=3306)
    # print(jsonData)
    # print(type(filename)=='str')

    if (isinstance(jsonData,str)):
        # 获取数据库游标
        cursor = conn.cursor()
        jsonList=json.loads(jsonData)
        # tmp是list类型
        tmp=jsonList['image']
        result=jsonList['result']
        usedTime=jsonList['usedTime']
        timeNow=jsonList['timeNow']
        # name = str(usedTime)+result+'.jpg'
        # img是bytes类型
        img = base64.b64decode(str(tmp))
        # mysql命令
        sql = 'insert into images(img,result,usedTime,timeNow) values(%s,%s,%s,%s)'
        cursor.execute(sql, (img, result,usedTime,timeNow))
        cursor.close()
        conn.commit()
        # image_data是numpy.ndarray类型
        # image_data = np.fromstring(img, np.uint8)
        # image_data = cv2.imdecode(image_data, cv2.IMREAD_COLOR)
        # cv2.imwrite('D:/vanderlandeProjectImg/dailytest/901/{}'.format(name), image_data)
        # cv2.imwrite(r'D:\vanderlandeProjectImg\dailytest\901\test.jpg', image_data)
    else:
        tmp=jsonData['image']
        img = base64.b64decode(str(tmp))
        image_data = np.fromstring(img, np.uint8)
        image_data = cv2.imdecode(image_data, cv2.IMREAD_COLOR)
        # cv2.imwrite(r'D:\vanderlandeProjectImg\dailytest\831\1.jpg', image_data)
    json_info = json.dumps(dic, ensure_ascii=False)
    return json_info


if __name__ == "__main__":
    dic = {}
    # app.run(host='10.16.55.26',port=9000)
    app.run(host='192.168.0.7',port=8000)
    ## Serve the app with gevent
    # http_server = WSGIServer(('0.0.0.1',5000),app)
    # http_server.serve_forever()
